import {Injectable} from '@angular/core';
import {Http,Response} from '@angular/http';
import {User} from "../model/user-model";
import {Observable, Subject} from 'rxjs';

@Injectable()
export class UserLoginService {
  public loginURL = 'http://localhost:3000/login';
  public logoutURL = 'http://localhost:3000/logout';
  public subject: Subject<User> = new Subject<User>();

  constructor(public http: Http) {
  }

  public get currentUser(): Observable<User> {
    return this.subject.asObservable();
  }

  public login(user: User) {
    return this.http.post(this.loginURL, user)
      .map((response: Response) => {
      let user = response.json();
      if(!user.error){
        localStorage.setItem('currentUser',JSON.stringify(user));
        this.subject.next(Object.assign({},user));
      }
        return user;
      })
  }

  public logout():void{
    localStorage.removeItem('currentUser');
    this.subject.next(Object.assign({}));
    this.http.get(this.logoutURL);
  }
}
